package com.blogspot.nhu313.myhistory;

import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.blogspot.nhu313.myhistory.category.CategoryService;
import com.blogspot.nhu313.myhistory.category.to.Category;
import com.blogspot.nhu313.myhistory.service.ServiceFactory;
import com.blogspot.nhu313.myhistory.service.ServiceName;

public class MainActivity extends ListActivity {

	private List<Category> categories;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int parentCategoryId = getParentCategoryId();
    	categories = getCategories(parentCategoryId);
        this.setListAdapter(new ArrayAdapter<Category>(this, R.layout.list_item, R.id.label, categories));
        addListener();
    }

	private List<Category> getCategories(int parentCategoryId) {
		CategoryService categoryService = ServiceFactory.getService(ServiceName.CATEGORY, getApplicationContext());
        return categoryService.getCategories(parentCategoryId);
	}

    private int getParentCategoryId() {
    	Intent intent = new Intent();
    	final int categoryId = intent.getIntExtra(SharedKey.CATEGORY_ID.value(), 0);
		return categoryId;
	}


	private void addListener() {
        ListView listView = getListView();
        listView.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {
        	  Category selectedCategory = categories.get(position);
        	  categories = getCategories(selectedCategory.getId());
          }
        });
	}
    
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }   
}